﻿@Cofe ?= {}

$ = jQuery
Entry = Cofe.Entry
EntryItemList = Cofe.EntryItemList
EntryItem = Cofe.EntryItem
EntryList = Cofe.EntryList
Link = Cofe.Link
utils = Cofe.utils
paginateSupport = Cofe.paginateSupport
uploadSupport = Cofe.uploadSupport


class EntryListView extends Spine.Controller  
  @include Cofe.uploadSupport

  elements : 
    ".prevPage" : "elePrevPage"
    ".nextPage" : "eleNextPage"
    ".displayMore" : "eleDisplayMore"
    ".totalPages" : "eleTotalPages"
    ".currentPage" : "eleCurrentPage"

  events :
    "click .prevPage" : "goPrevPage"
    "click .nextPage" : "goNextPage"
    "click .displayMore" : "addNextPage"
    
  waypoint : false
  select : 'none'
  path : undefined

  constructor : (params) ->    
    
    super
    
  init : () ->
    @entryItemList = new EntryItemList({ el : $('.entries', @el), waypoint : @waypoint, select : @select })
    @entryItemList.bind('itemAdded', @itemAdded)
    @entryItemList.bind('itemRemoved', @itemRemoved)
    @entryItemList.bind('refreshing', @refreshing)
    @entryItemList.bind("selected", (s, items) => @trigger("selectionChanged", @, (e.entry for e in items)))
    @entryItemList.bind('error', @error)
    
    @initUploadSupport(@el, @rootEntryItem)

  changeUrlPath : (url, rootEntryItem) ->
    @rootEntryItem = if rootEntryItem is undefined then null else rootEntryItem
    if @url isnt url      
      @entryItemList.changeUrlPath(url)

  #selected : (selectedItems) ->
    #@selectedItems = selectedItems    
    #console.log("EntryListView: Selected "+ selectedItems.length + " items.")
    #@trigger("selected", @, selectedItems)

  refreshing : (sender, entryList) =>
    @elePrevPage.button({ disabled: !sender.hasPrevPage() });
    @eleNextPage.button({ disabled: !sender.hasNextPage() });
    @eleTotalPages.html(entryList.totalPages)
    @eleCurrentPage.html(entryList.currentPage)

  refresh : (entryList) ->
    @

  # Overridable, called by OnItemAdded after an item added during refresh
  itemAdded : (sender, entryItem, idx) =>
      entryItem.bind("clicked", (ei) =>        
        @trigger("itemClicked", @, ei.entry)
      )
  
  # Overridable, called by OnItemRemoved after an item added during refresh
  itemRemoved : (sender, entryItem, idx) =>
    entryItem.unbind("itemClicked")
            
  error : (sender, errorStr, url) =>
    @trigger("error", sender, errorStr, url)

  goPrevPage : () ->
    @entryItemList.goPrevPage()

  goNextPage : () ->
    @entryItemList.goNextPage()

  addNextPage : () ->
    @entryItemList.addNextPage()

Cofe.EntryListView = EntryListView
